package RationalNumber;

public class RationalNumber {
	private int numerator;
	private int denominator;
	
	public RationalNumber(int numerator,int denominator) {
		this.numerator = numerator;
		this.denominator = denominator;
		if(this.isDenominatorZero(this.denominator)==true) { //分母为0强制退出；
			System.out.println("分母不能为0！");
			System.exit(-1);
		}
	}
	private boolean isDenominatorZero(int denominator) { //判断分母是否为0
		if(denominator==0)
			return true;
		else
			return false;
	}
	private boolean isNumeratorZero(int numerator) { //判断分子是否为0
		if(numerator==0)
			return true;
		else
			return false;
	}
	public int getNumberator() { //获取分子
		return this.numerator;
	}
	public int getDenominator() { //获取分母
		return this.denominator;
	}
	public int gcd() { //约分
		int t,m,n;
		m=this.denominator;
		n=this.numerator;
		while(m % n != 0) {
			t=n;
			n=m%n;
			m=t;
		}
		this.denominator /= n;
		this.numerator /= n;
		return n;
	}
	public RationalNumber add(RationalNumber num) {  //加法
		RationalNumber sum = new RationalNumber(0,1);
		sum.denominator=num.denominator*this.denominator;
		sum.numerator=num.denominator*this.numerator+num.numerator*this.denominator;
		if(sum.isNumeratorZero(sum.numerator)==false && sum.isDenominatorZero(sum.denominator)==false)
		{
			sum.gcd();
		}
		
		return sum;
	}
	public RationalNumber subtraction(RationalNumber num) {  //减法
		RationalNumber difference = new RationalNumber(0,1);
		RationalNumber temp = new RationalNumber(num.numerator,num.denominator);
		temp.denominator = num.denominator;
		temp.numerator = -num.numerator;
		difference = this.add(temp);
		
		return difference;
	}
	public RationalNumber multiply(RationalNumber num) {  //乘法
		RationalNumber product = new RationalNumber(0,1);
		
		product.numerator=this.numerator*num.numerator;
		product.denominator=this.denominator*num.denominator;
		if(product.isNumeratorZero(product.numerator)==false)
		product.gcd();
		
		return product;
	}
	public RationalNumber division(RationalNumber num) {  //除法
		RationalNumber quotient = new RationalNumber(0,1);
		RationalNumber temp = new RationalNumber(num.numerator,num.denominator);
		
		quotient = this.multiply(temp);
		
		return quotient;
	}
	
	public boolean equals(RationalNumber num) {  //判断两个有理数是否相等；
        RationalNumber temp = new RationalNumber(this.numerator,this.denominator);
		temp.gcd();
		num.gcd();
		if(temp.denominator==num.denominator && temp.numerator==num.numerator) {
			return true;
		}
		else {
			return false;
		}
	}
	public double doubleValue() {  //转换为double型；
		return (double)this.numerator/this.denominator;
	}
	public int intValue() {   //取整数部分；
		return this.numerator/this.denominator;
	}
	public String toString() {  //得到该有理数的字符串形式
		
		return this.numerator+"/"+this.denominator;
	}
}

